import React from 'react';
import ReactDOM from 'react-dom';
import thunk from 'redux-thunk';
import {createStore, combineReducers, applyMiddleware} from 'redux';
import fetch from 'isomorphic-fetch';
import fetchReducer from './reducers/fetchReducer';
const store = createStore(fetchReducer, applyMiddleware(thunk));
class SampleCom extends React.Component {
	fetchData() {
		this.props.dispatch(getData("FETCH_DATA"))
	}
	render() {
		let list = [];
		if(this.props.data.list) {
			list = this.props.data.list.map(function(item, idx){
				return <li key={idx}>{item.name} {item.age}</li>;
			})
		}
		return (
			<div>
				{this.props.data.status}<br/>
				<ul>
				{list}
				</ul>
				<button onClick={this.fetchData.bind(this)}>请求ajax</button>
			</div>
		)
	}
}
const getData = postTitle => (dispatch, getState) => {
	dispatch({
		type: postTitle + "_START"
	});
	// 做异步处理，比如ajax，在回调中再次dispatch
	fetch("/data_api/users/")
	.then(function(response){
		return response.json();
	})
	.then(function(json){
		dispatch({
			type: postTitle + "_FINISH",
			payload: json
		});
	})
};
function render() {
	ReactDOM.render(
		<SampleCom data={store.getState()} dispatch={(arg)=>{store.dispatch(arg)}} />,
		document.getElementById("example")
	);
}
render();
store.subscribe(render);
